<?php
/**
 * 用户模型监听事件（批量更新时不会触发相应事件，因为是直接走查询构建器完成的，绕过了模型方法。20190624 add，自增自减也不会触发）
 * 参考 https://www.jianshu.com/p/5bd857a0ceed
 * Created by PhpStorm.
 * User: eric
 * Date: 2019/6/24
 * Time: 15:26
 */

namespace App\Http\Repositories\Observers;

use App\Http\Repositories\Redis\UserRedis;
use App\Models\Users;
use Illuminate\Support\Facades\Log;

class UserObserver
{
    //触发需要更新哈希表的字段 （跟UserRedis缓存字段一致）
    protected $updateFields = ['username', 'nickname', 'mobile',  'avatar', 'level', 'status','role_value','role_student_status','role_teacher_status'];

    public function saved(Users $user)
    {
        //        Log::info('已经保存用户到数据库[' . $user->id . ']' . $user->name);
        $userId = $user->id;
        // 基于更新的数据更新部分字段
        $needUpdate = $this->checkNeedUpdate($user);
        if ($needUpdate == 1) {
            Log::info('用户' . $userId . '更新基本信息', ['update_arr' => $user->getChanges()]);
            return UserRedis::getRedisInstance()->updateNode($userId);
        } else {
            return false;
        }
    }

    public function created(Users $user)
    {


    }

    public function deleted(Users $user)
    {
        //        Log::info('已经删除用户[' . $user->id . ']' . $user->name);
        $userId = $user->user_id;
        UserRedis::getRedisInstance()->deleteHash($userId);
    }

    /**
     * 判断是否需要更新hash表数据
     * @param $orm
     * @return int
     */
    private function checkNeedUpdate($orm)
    {
        // 基于更新的数据更新部分字段
        $needUpdate = 0;
        $aChanges   = $orm->getChanges();
        foreach ($aChanges as $key => $value) {
            if (in_array($key, $this->updateFields)) {
                $needUpdate = 1;
                break;
            }
        }

        return $needUpdate;
    }

}
